const router = require('koa-router')()
const Users = require('../models/users')
const jsonwebtoken = require('jsonwebtoken')
const {auth} = require("../utils");
// 用户信息
router.get('/', auth, async function (ctx, next) {
  ctx.body = await Users.findById(ctx.state.user._id).populate('shop');
})

// 用户列表
router.get('/li', async function (ctx, next) {
  ctx.body = await Users.find().populate('shop')
})

// 修改用户信息
router.put('/', function (ctx, next) {
  ctx.body = '修改用户信息'
})

// 注册用户
router.post('/', async function (ctx, next) {

  ctx.verifyParams({
    name: {type: "string", required: true},
    password: {type: "string", required: true}
  })
  let oldUser = await Users.findOne().sort({'createdAt':-1})
  ctx.request.body.id = oldUser?oldUser.id+1:100000
  ctx.body = await new Users(ctx.request.body).save()
})

// 登陆用户
router.post('/login', async function (ctx, next) {
  ctx.verifyParams({
    id: {type: "number", required: true},
    password: {type: "string", required: true}
  })
  let _user = await Users.findOne(ctx.request.body)
  if (!_user){
    ctx.throw(401, '用户名或密码不正确');
  }else {
    let obj = {
      _id:_user._id,
      id:_user.id,
      name:_user.name
    }
    let token = await  jsonwebtoken.sign(obj, 'ct123', {expiresIn: '7d'})
    ctx.body = Object.assign({user:_user},{token:token})
  }
})

// 成为骑手
router.post('/deliver', auth, async function (ctx, next) {
  await Users.findByIdAndUpdate(ctx.state.user._id, {deliver: true})
  ctx.body = await Users.findById(ctx.state.user._id)
})







module.exports = router
